// pages/profile/profile.js
import Cache from '../../utils/cache';
import Tool from '../../utils/tool';
import api from '../../utils/api';
import { myRequest } from '../../utils/request';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        confirmType: 0,  // 1：删除歌单提示
        showMusicMenuModal: false, // 保存歌单模态框
        showConfirmModel: false, // 确认信息提示模态框
        showEditUserModel: false, // 修改个人信息模态框
        confirmText: '',  // 确认提示内容
        selfMusicMenuList: [],  // 自建歌单列表
        musicMenu: {
            title: '',
            name: '',
            viewPhoto: api.BASE_URL + '/photo/view?filename=common/no_image.jpg',
            id: '',
            coverPhoto: 'common/no_image.jpg',
            token: ''
        },
        loginUser: {}, // 当前登录用户信息
        editUser: {
            username: '',
            password: '',
            headPic: '',
            viewPhoto: '',
            phone: '',
            id: '',
            token: ''
        },
        collectList: [],
        recentListenList: []
    },


   // 打开上传歌单封面图片的页面
   openUploadCoverPhoto(event) {
        const data = event.currentTarget.dataset;
        let _this = this;
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album'],
            success(res) {
                let file = res.tempFiles[0].tempFilePath;
                // 获取文件后缀
                const fileFormat = file.substring(file.lastIndexOf(".") + 1, file.length);
                const fileManager = wx.getFileSystemManager();
                const base64 = fileManager.readFileSync(file, 'base64');
                _this.uploadCoverPhoto(`data:image/${fileFormat};base64,${base64}`, data.type);
            },
            fail(res) {
                wx.showToast({
                    title: '上传失败',
                    icon: 'error'
                })
            }
        })
    },

    async uploadCoverPhoto(base64, type) {
        const res = await myRequest({
        url: '/photo/app_upload',
        method: 'POST',
        data: {photoBase64: base64}
        });
        if(res.data.code === 0) {
            wx.showToast({
            title: '上传成功！',
            icon: 'success'
            })
            if(type === 'musicMenu') {
                this.setData({
                    ['musicMenu.coverPhoto']: res.data.data,
                    ['musicMenu.viewPhoto']: api.BASE_URL + '/photo/view?filename=' + res.data.data
                })
            } else if (type === 'user') {
                this.setData({
                    ['editUser.headPic']: res.data.data,
                    ['editUser.viewPhoto']: api.BASE_URL + '/photo/view?filename=' + res.data.data
                })
            }
        } else {
            wx.showToast({
                title: res.data.msg,
                icon: 'none'
            })
        }
    },

    // 跳转到音乐列表页面
    goToMusicList(event) {
        const data = event.currentTarget.dataset
        wx.navigateTo({
            url: `/pages/musicList/musicList?type=${data.type}&searchId=${data.id}`
        })
    },

    // 保存歌单信息
    async confirmSaveMusicMenu() {
        const res = await myRequest({
            url: '/app/music/menu/save',
            method: 'POST',
            data: this.data.musicMenu
        });
        if(res.data.code === 0) {
            wx.showToast({
            title: res.data.msg,
            icon: 'success'
            })
            this.setData({showMusicMenuModal: false})
            this.getSelfMusicMenuList();
        } else {
            wx.showToast({
                title: res.data.msg,
                icon: 'none'
            })
        }
    },

    // 获取用户收藏的音乐数据
    async getCollectList() {
        const res = await myRequest({
            url: '/app/collect/getByUserId',
            method: 'POST',
            data: {token : this.data.editUser.token}
        });
        if(res.data.code === 0) {
            let result = res.data.data;
            result.forEach(item => {
                item.viewPhoto = api.BASE_URL + '/photo/view?filename=' + item.coverPhoto;
            })
            this.setData({collectList: result});
        } else {
            wx.showToast({
                title: res.data.msg,
                icon: 'none'
            })
            wx.reLaunch({
                url: '/pages/login/login'
            })
        }
    },

    // 获取用户最近播放的音乐数据
    async getRecentListenMusicList() {
        const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
        const res = await myRequest({
            url: '/app/recent/listen/getTenMusic',
            method: 'POST',
            data: {token : loginUser}
        });
        if(res.data.code === 0) {
            let result = res.data.data;
            result.forEach(item => {
                item.viewPhoto = api.BASE_URL + '/photo/view?filename=' + item.coverPhoto;
            })
            this.setData({recentListenList: result});
        } else {
            wx.showToast({
                title: res.data.msg,
                icon: 'none'
            })
            wx.reLaunch({
                url: '/pages/login/login'
            })
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.authUser();
        this.getLoginUser();
        this.getSelfMusicMenuList();
        this.getCollectList();
        this.getRecentListenMusicList();
    },

    async getLoginUser() {
        const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
        const res = await myRequest({
            url: '/app/user/getLoginUser',
            method: 'POST',
            data: {token : loginUser}
        });
        if(res.data.code === 0) {
            let result = res.data.data;
            result.viewPhoto = api.BASE_URL + '/photo/view?filename=' + result.headPic;
            if(result.roleId === 1) {
                result.role = '普通用户';
            } else if (result.roleId === 2) {
                result.role = '管理员';
            }
            this.setData({loginUser: result, editUser: result});
        } else {
            wx.reLaunch({
                url: '/pages/login/login'
            })
        }
    },

    // 获取当前用户的自建歌单列表
    async getSelfMusicMenuList() {
        const res = await myRequest({
            url: '/app/music/menu/getByUserId',
            method: 'POST',
            data: {token : this.data.musicMenu.token}
        });
        if(res.data.code === 0) {
            let result = res.data.data;
            result.forEach(item => {
                item.viewPhoto = api.BASE_URL + '/photo/view?filename=' + item.coverPhoto;
            })
            this.setData({selfMusicMenuList: result});
        } else {
            wx.showToast({
                title: res.data.msg,
                icon: 'none'
            })
            wx.reLaunch({
                url: '/pages/login/login'
            })
        }
    },

    // 打开新建歌单弹窗
    openAddMusicMenu() {
        const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
        let data = {
            title: '新建歌单',
            name: '',
            viewPhoto: api.BASE_URL + '/photo/view?filename=common/no_image.jpg',
            id: '',
            coverPhoto: 'common/no_image.jpg',
            token: loginUser
        };
        this.setData({showMusicMenuModal: true, musicMenu: data});
    },

    // 打开修改个人信息的弹窗
    openEditUserModel() {
        this.setData({showEditUserModel: true});
    },

    // 关闭修改个人信息的弹窗
    cancelShowEditUser() {
        this.setData({showEditUserModel: false});
    },

    // 确认修改个人信息
    async confirmSaveEditUser() {
        this.authUser();
        const res = await myRequest({
            url: '/app/user/editInfo',
            method: 'POST',
            data: this.data.editUser
        });
        if(res.data.code === 0) {
            wx.showToast({
              title: res.data.msg,
              icon: 'success'
            })
            this.cancelShowEditUser();
            this.getLoginUser();
        } else {
            wx.showToast({
                title: res.data.msg,
                icon: 'none'
            })
        }
    },

    // 歌单表单项内容发生改变的回调
    handleMusicMenuInput(event) {
        let type = event.currentTarget.dataset.type;  
        this.setData({
            // type是变量，对象里面操作属性用中括号
            ['musicMenu.' + type]: event.detail.value
        })
    },

    // 用户表单项内容发生改变的回调
    handleUserInput(event) {
        let type = event.currentTarget.dataset.type;  
        this.setData({
            // type是变量，对象里面操作属性用中括号
            ['editUser.' + type]: event.detail.value
        })
    },

    // 打开删除歌单确认提示
    openShowRemoveMusicMenu(event) {
        const data = event.currentTarget.dataset;
        this.setData({
            ['musicMenu.id']: data.id
        });
        this.setData({showConfirmModel: true, confirmText: '确认要删除此歌单吗？',  confirmType: 1});
    },

    // 关闭删除歌单确认提示
    cancelShowConfirmModel() {
        this.setData({showConfirmModel: false, confirmText: '',  confirmType: 0});
    },

    // 确认提示点击确定
    confirmShowModel() {
        if(this.data.confirmType === 1) {
            this.removeMusicMenu();
        }
    },

    // 删除歌单操作
    async removeMusicMenu() {
        const res = await myRequest({
            url: '/app/music/menu/remove',
            method: 'POST',
            data: {id: this.data.musicMenu.id}
        });
        if(res.data.code === 0) {
            wx.showToast({
            title: res.data.msg,
            icon: 'success'
            })
            this.setData({showConfirmModel: false});
            this.getSelfMusicMenuList();
        } else {
            wx.showToast({
                title: res.data.msg,
                icon: 'none'
            })
        }
    },

    // 保存歌单信息
    async confirmSaveMusicMenu() {
        const res = await myRequest({
            url: '/app/music/menu/save',
            method: 'POST',
            data: this.data.musicMenu
        });
        if(res.data.code === 0) {
            wx.showToast({
            title: res.data.msg,
            icon: 'success'
            })
            this.setData({showMusicMenuModal: false})
            this.getSelfMusicMenuList();
        } else {
            wx.showToast({
                title: res.data.msg,
                icon: 'none'
            })
        }
    },

    // 打开编辑歌单弹窗
    openEditMusicMenu(event) {
        const data = event.currentTarget.dataset;
        const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
        let editItem = data.item;
        editItem.token = loginUser;
        editItem.title = "编辑歌单";
        this.setData({showMusicMenuModal: true, musicMenu: editItem})
    },

    // 退出登录
    logout() {
        Cache.removeCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
        wx.reLaunch({
            url: '/pages/music/music'
        });
    },

    toMusicPlayer(event) {
        const data = event.currentTarget.dataset; 
        let music = data.music;
        delete music['viewPhoto'];
        wx.navigateTo({
          url: '/pages/player/player?music=' + JSON.stringify(music),
        })
    },

    cancelShowMusicMenu() {
        this.setData({showMusicMenuModal: false})
    },

    /**
     * 验证用户是否登录
     */
    authUser() {
        const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
        if(Tool.isEmpty(loginUser)) {
            wx.reLaunch({
                url: '/pages/login/login'
            })
        }
        this.setData({
            ['musicMenu.token'] : loginUser,
            ['editUser.token'] : loginUser
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.authUser();
        this.getLoginUser();
        this.getSelfMusicMenuList();
        this.getCollectList();
        this.getRecentListenMusicList();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})